package com.zb.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zb.client.SkuFeignClient;
import com.zb.dto.SkuDto;
import com.zb.dto.SpuDto;
import com.zb.entity.TbOrderItemModel;
import com.zb.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate<String,Object>redisTemplate;

    @Autowired
    private SkuFeignClient skuFeignClient;

    @Override
    public Integer addCart(String skuId, int num, String username) {
        String redisKey = "cart:" + username;
        if (num <= 0) {
            redisTemplate.boundHashOps(redisKey).delete(skuId);
            return 1;
        }
        Map<String, Object> info = skuFeignClient.info(skuId);
        Map mapSku = (Map) info.get("sku");
        Map mapspu = (Map) info.get("spu");

        SkuDto skuDto = JSON.parseObject(JSON.toJSONString(mapSku), SkuDto.class);
        SpuDto spuDto = JSON.parseObject(JSON.toJSONString(mapspu), SpuDto.class);

        TbOrderItemModel orderItemModel = new TbOrderItemModel();
        orderItemModel.setId(String.valueOf(IdWorker.getId()));
        orderItemModel.setCategoryId1(spuDto.getCategory1Id());
        orderItemModel.setCategoryId2(spuDto.getCategory2Id());
        orderItemModel.setCategoryId3(spuDto.getCategory3Id());
        orderItemModel.setSpuId(spuDto.getId());
        orderItemModel.setSkuId(skuDto.getId());
        orderItemModel.setName(skuDto.getName());
        orderItemModel.setPrice(skuDto.getPrice());
        orderItemModel.setNum(num);
        orderItemModel.setMoney(skuDto.getPrice() * num);
        redisTemplate.boundHashOps(redisKey).put(skuId, orderItemModel);
        return 1;
    }

    @Override
    public List<TbOrderItemModel> list(String username) {
        String redisKey="cart:" + username;
        List values = redisTemplate.boundHashOps(redisKey).values();
        return values;
    }

    @Override
    public Integer delete(String[] skuIds, String username) {
        String redisKey = "cart:" + username;
        Long delete = redisTemplate.boundHashOps(redisKey).delete(skuIds);
        return delete.intValue();
    }

    @Override
    public List<TbOrderItemModel> buyList(String[] skuIds, String username) {
        List<TbOrderItemModel> list = new ArrayList<>();
        String redisKey = "cart:" + username;
        for (String skuId : skuIds) {
            list.add((TbOrderItemModel) redisTemplate.boundHashOps(redisKey).get(skuId));
        }
        return list;
    }
}
